package com.plugins.server;

import java.util.Date;

import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import com.iclient.dao.service.WbUserService;
import com.plugins.http.MyWbFollows;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

/**
 * 
 * @Author  zziahui
 * @Descp   rabbitMq客户端工作线程
 *
 */
public class MsgConsumer extends DefaultConsumer{
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	@Autowired
	private WbUserService wbUserService;
	
	/**
	 * 父类的构造方法
	 * @param channel
	 */
	public MsgConsumer(Channel channel) {
		super(channel);
	}
	
	

	/**
	 * 重写父类的消费方法
	 */
	@Override
	public void handleDelivery(String consumerTag, Envelope envelope,
			BasicProperties properties, byte[] body){
		try{
			String routekey = envelope.getRoutingKey();
			switch (routekey) {
				case "unfollow":
					MyWbFollows.unFollow(new String(body));
					break;
				case "follow":
					Integer code = MyWbFollows.followUser(new String(body));
					if(code == 200){
						wbUserService.updateByUrl(new String(body));
						redisTemplate.opsForHash().increment("follow:size", DateFormatUtils.format(new Date(), "yyyy-MM-dd"), 1);
					}
				default:
					break;
			}
		}
		finally{
			MQServer mqServer = MQServer.getServer();
			mqServer.ackMessage(this.getChannel(), envelope.getDeliveryTag());
		}
		try {
			Thread.sleep(60*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
	
}